from urllib import request,parse
from http.cookiejar import  CookieJar

headers = {
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36",
}

#处理登录 保存cookie
def get_opener():
    #1.创建 cookiejar 对象
    cookiejar = CookieJar()
    #2.使用cookiejar 创建一个HttpCookieProcessor 对象  就是我们的句柄 handler
    handler = request.HTTPCookieProcessor(cookiejar)
    #3.使用handler 创建 opener
    opener = request.build_opener(handler)
    return opener


def login_renren(opener):
    #使用opener 发送请求
    data = {
        'email':'gaohj5@163.com',
        'password':'12qwaszx'
    }

    login_url = "http://www.renren.com/PLogin.do"

    req = request.Request(login_url,data=parse.urlencode(data).encode('utf-8'),headers=headers)
    response = opener.open(req)
    print(response.read().decode('utf-8'))

def visit_profile(opener):
    my_url = "http://www.renren.com/541197383/profile"
    req= request.Request(my_url,headers=headers)

    resp = opener.open(req)

    with open('renren2.html','w',encoding='utf-8') as fp:
        fp.write(resp.read().decode('utf-8'))


if __name__ == "__main__":
    opener = get_opener()
    login_renren(opener)
    visit_profile(opener)



